package com.aviccxzx.smarthome.UserModule;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.aviccxzx.smarthome.R;
import com.aviccxzx.smarthome.base.BaseActivity;
import com.aviccxzx.smarthome.entity.CamMsgBean;
import com.aviccxzx.smarthome.netutil.app.App;
import com.aviccxzx.smarthome.service.RetrofitHelper;
import com.aviccxzx.smarthome.service.RetrofitService;
import com.jovision.AppConsts;
import com.jovision.JVNetConst;
import com.jovision.JniUtil;
import com.jovision.sovplay.JVRemotePlayBackActivity;
import com.jovision.sovplay.SovUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by joey on 2016/10/25.
 */
public class CamMsgActivity extends BaseActivity implements View.OnClickListener {
    CamMsgAdapter msgAdapter;
    ListView cam_msg_list;
    String yst = "";
    List<CamMsgBean.DataBean> msgList;
    int version;//摄像机的高低版本
    private ProgressDialog progressDialog;
    SwipeRefreshLayout layout_swipe_refresh;
    public void showProgressDialog(String msg) {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        progressDialog = new ProgressDialog(this, ProgressDialog.THEME_DEVICE_DEFAULT_LIGHT);
        progressDialog.setMessage(msg);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(true);
        try {
            progressDialog.show();
        } catch (WindowManager.BadTokenException exception) {
            exception.printStackTrace();
        }
    }

    /**
     * 取消对话框显示
     */
    public void disMissDialog() {
        try {
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
                progressDialog = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initSettings() {

    }

    @Override
    protected void initUi() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setContentView(R.layout.cam_msglist_lay_v19);
        } else {
        }
        ((TextView) findViewById(R.id.title_tv)).setText("报警记录");
        findViewById(R.id.ll_title_left_view).setOnClickListener(this);
        yst = getIntent().getStringExtra("yst");
        version = getIntent().getIntExtra("version",0);
        cam_msg_list = (ListView) findViewById(R.id.cam_msg_list);
        layout_swipe_refresh = (SwipeRefreshLayout)findViewById(R.id.layout_swipe_refresh);
        msgList = new ArrayList<>();
        msgAdapter = new CamMsgAdapter();
        cam_msg_list.setAdapter(msgAdapter);
        getMsg();
        layout_swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                msgList.clear();
                getMsg();
                layout_swipe_refresh.setRefreshing(false);
            }
        });
    }

    @Override
    protected void saveSettings() {

    }

    @Override
    protected void freeMe() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initUi();
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_title_left_view:
                finish();
                break;
        }
    }

    /**
     * 获取报警消息列表
     */
    public void getMsg() {
        RetrofitService service = RetrofitHelper.getInstance(this).getServer();
        Call<CamMsgBean> call = service.getCamHistory(yst);
        call.enqueue(new Callback<CamMsgBean>() {
            @Override
            public void onResponse(Call<CamMsgBean> call, Response<CamMsgBean> response) {
                if (response.body() != null && response.body().getData() != null) {
                    msgList.clear();
                    msgList.addAll(response.body().getData());
                    msgAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<CamMsgBean> call, Throwable t) {
            }
        });
    }

    @Override
    public void onNotify(int what, int arg1, int arg2, Object obj) {
        handler.sendMessage(handler.obtainMessage(what, arg1, arg2, obj));
    }

    @Override
    public void onHandler(int what, int arg1, int arg2, Object obj) {
        switch (what) {
            // 下载进度
            //DT_FILE_TAIL
            case JVNetConst.CALL_CATEYE_SENDDATA: {
                com.alibaba.fastjson.JSONObject data = JSON.parseObject(obj.toString());
                int result = data.getInteger("result");
                disMissDialog();
                if (result == 1) {
//                    Toast.makeText(CamMsgActivity.this, "下载成功", Toast.LENGTH_LONG).show();
                    show(downFileFullName);
                } else {
                    Toast.makeText(CamMsgActivity.this, "下载失败", Toast.LENGTH_LONG).show();
                }
                break;
            }
        }
    }

    private int window = 0;
    String downFileFullName = "";

    public class CamMsgAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return msgList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(final int i, View convertView, ViewGroup viewGroup) {
            View view = null;

            if (convertView != null) {
                view = convertView;
            } else {
                view = LayoutInflater.from(CamMsgActivity.this).inflate(R.layout.cam_msglist_item_lay, viewGroup, false);
            }

            ViewHolder holder = (ViewHolder) view.getTag();
            if (holder == null) {
                holder = new ViewHolder();
                view.setTag(holder);
            }
            holder.cam_msg_time = (TextView) view.findViewById(R.id.cam_msg_time);
            holder.cam_msg_img = (ImageView) view.findViewById(R.id.cam_msg_img);
            holder.cam_msg_video = (ImageView) view.findViewById(R.id.cam_msg_video);

            if (version == 0){
                //低版本 不显示视频
                holder.cam_msg_video.setVisibility(View.INVISIBLE);
            }else {
                //高版本 显示视频
                holder.cam_msg_video.setVisibility(View.VISIBLE);
            }

            holder.cam_msg_time.setText(formatData("yyyy-MM-dd HH:mm:ss", msgList.get(i).getAlarmTime() - 28800));
//            if (!TextUtils.isEmpty(msgList.get(i).getImage().toString())) {
//                if (!msgList.get(i).getImage().toString().equals("")){
//                    holder.cam_msg_img.setImageBitmap(getBitmapByWidth(msgList.get(i).getImage().toString(), 50, 60));
//                }
//            }
            holder.cam_msg_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    /*String fileName = System.currentTimeMillis()
                            + AppConsts.IMAGE_JPG_KIND;
                    downFileFullName = AppConsts.DOWNLOAD_PATH + fileName;
                    JniUtil.setDownloadFileName(window, downFileFullName);
                    SovUtil.startStreamDownload(window, "/progs/rec/00/20170823/M01142356.jpg");*/
                    if (!TextUtils.isEmpty(msgList.get(i).getImage().toString())&&!msgList.get(i).getImage().toString().equals("")) {
                        showProgressDialog("加载中...");
                        String fileName = System.currentTimeMillis()
                                + AppConsts.IMAGE_JPG_KIND;
                        downFileFullName = AppConsts.DOWNLOAD_PATH + fileName;
                        JniUtil.setDownloadFileName(0, downFileFullName);
                        SovUtil.startStreamDownload(0, msgList.get(i).getImage().toString());
                    } else {
                        App.getApp().showToast("没有照片，请查看摄像机是否安装存储卡");
                    }
                }
            });
            holder.cam_msg_video.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!TextUtils.isEmpty(msgList.get(i).getVideo().toString())) {
                        Intent intent = new Intent();
                        intent.setClass(CamMsgActivity.this,
                                JVRemotePlayBackActivity.class);
                        intent.putExtra("window", 0);
                        intent.putExtra("acBuffStr", msgList.get(i).getVideo().toString());
                        CamMsgActivity.this.startActivity(intent);
                    } else {
                        App.getApp().showToast("没有视频，请查看摄像机是否安装存储卡并设置报警录像模式");
                    }

                }
            });

            return view;
        }

        public class ViewHolder {
            TextView cam_msg_time;
            ImageView cam_msg_img;
            ImageView cam_msg_video;
        }
    }

    RelativeLayout layout;
    AlertDialog alertDialog;

    public void show(String imgPath) {
        layout = (RelativeLayout) LayoutInflater.from(CamMsgActivity.this).inflate(R.layout.msg_show_img, null);
        alertDialog = new AlertDialog.Builder(CamMsgActivity.this).create();
        ImageView img = (ImageView) layout.findViewById(R.id.show_img);
        //        img.setImageBitmap(getRotateBitmap(2, imgPath));
        img.setImageBitmap(BitmapFactory.decodeFile(imgPath));

        alertDialog.show();

        alertDialog.setContentView(layout);
        Window window = alertDialog.getWindow();
        ViewGroup.LayoutParams layoutParams = window.getAttributes();
        WindowManager manager = window.getWindowManager();
        Display display = manager.getDefaultDisplay();
        layoutParams.width = (int) (display.getWidth() * 0.9);
        layoutParams.height = (int) (display.getHeight() * 0.6);
        window.setAttributes((WindowManager.LayoutParams) layoutParams);
    }

    /**
     * 图片旋转
     *
     * @param type
     * @param bitmapPath
     * @return
     */
    public Bitmap getRotateBitmap(int type, String bitmapPath) { // type 1
        // 竖屏显示图片，2
        // 横屏显示图片

        Bitmap bitmap = BitmapFactory.decodeFile(bitmapPath);

        Bitmap resultBitmap = bitmap;
        int height = bitmap.getHeight();
        int width = bitmap.getWidth();

        System.out.println("获取的bitmap 宽和高：" + width + "：" + height);

        switch (type) {
            case 1: // 竖屏显示图片,需要偏高
                if (height < width) {
                    // 如果长度小于宽度，则需要选择，否则不需要旋转，只要将option修改即可
                    Matrix mmMatrix = new Matrix();
                    mmMatrix.postRotate(90f);

                    resultBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mmMatrix, true);
                }

                break;
            case 2: // 横屏显示图片，需要偏长
                if (height > width) {
                    // 如果宽度小于长度
                    Matrix mmMatrix = new Matrix();
                    mmMatrix.postRotate(90f);

                    resultBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mmMatrix, true);
                }

                break;

            default:
                break;
        }

        return resultBitmap;

    }

    /**
     * 获取缩略图
     *
     * @param localImagePath
     * @param width
     * @param addedScaling
     * @return
     */
    public Bitmap getBitmapByWidth(String localImagePath, int width, int addedScaling) {
        if (TextUtils.isEmpty(localImagePath)) {
            return null;
        }

        Bitmap temBitmap = null;

        try {
            BitmapFactory.Options outOptions = new BitmapFactory.Options();

            // 设置该属性为true，不加载图片到内存，只返回图片的宽高到options中。
            outOptions.inJustDecodeBounds = true;

            // 加载获取图片的宽高
            BitmapFactory.decodeFile(localImagePath, outOptions);

            int height = outOptions.outHeight;

            if (outOptions.outWidth > width) {
                // 根据宽设置缩放比例
                outOptions.inSampleSize = outOptions.outWidth / width + 1 + addedScaling;
                outOptions.outWidth = width;

                // 计算缩放后的高度
                height = outOptions.outHeight / outOptions.inSampleSize;
                outOptions.outHeight = height;
            }

            // 重新设置该属性为false，加载图片返回
            outOptions.inJustDecodeBounds = false;
            temBitmap = BitmapFactory.decodeFile(localImagePath, outOptions);
        } catch (Throwable t) {
            t.printStackTrace();
        }

        return temBitmap;
    }


    /**
     * 时间转换器
     *
     * @param dataFormat
     * @param timeStamp
     * @return
     */
    public static String formatData(String dataFormat, long timeStamp) {
        if (timeStamp == 0) {
            return "";
        }
        timeStamp = timeStamp * 1000;
        String result = "";
        SimpleDateFormat format = new SimpleDateFormat(dataFormat);
        result = format.format(new Date(timeStamp));
        return result;
    }
}
